package sysmiddleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/vueadmin/app/admin/internal/svc"
	"github.com/vueadmin/app/admin/sys"
	"github.com/vueadmin/app/admin/sys/sysvalidate"
	"github.com/vueadmin/utils"
	"github.com/vueadmin/utils/conv"
	"github.com/vueadmin/utils/response"
)

type CreateFieldMiddleware struct {
	svcCtx *svc.ServiceContext
}

func NewCreateFieldMiddleware(svcCtx *svc.ServiceContext) *CreateFieldMiddleware {
	return &CreateFieldMiddleware{
		svcCtx: svcCtx,
	}
}

// 创建数据表字段中间件
func (p CreateFieldMiddleware) Handle() gin.HandlerFunc {
	return func(c *gin.Context) {
		var data sys.Field
		var menu sys.Menu
		if err := utils.BindAndValid(c, &data); err != nil {
			response.Fail(c, err.Error())
			c.Abort()
			return
		}
		if err := new(sysvalidate.FieldValidate).Validate(&data); err != nil {
			response.Fail(c, err.Error())
			c.Abort()
			return
		}
		p.svcCtx.Db.Model(&sys.Menu{}).Where("menu_id", data.MenuId).Find(&menu)

		if data.OtherConfig["shuxing"] != nil {
			shuxing := data.OtherConfig["shuxing"].([]interface{})
			shuxingList := make([]string, 0)
			if len(shuxing) > 0 {
				for _, val := range shuxing {
					shuxingList = append(shuxingList, val.(string))
				}
			}
			if conv.IsValueInList("tabs", shuxingList) {
				var tabsCount int64
				if err := p.svcCtx.Db.Model(&sys.Field{}).Where("menu_id", data.MenuId).Where("other_config like ?", "%\"tabs%").Count(&tabsCount).Error; err != nil {
					response.Err(c, err)
					return
				}
				if tabsCount > 0 {
					response.Fail(c, "当前菜单已经设置选项卡字段")
					return
				}
			}
		}
		if sys.System.GetDBTypeByConnect(menu.Connect) != "mysql" {
			return
		}
		prefix := sys.System.GetPrefix(menu.Connect)

		if data.CreateTableField > 0 {
			if conv.Int8(menu.PageType) == 1 {
				var (
					defaultValue string
					length       string
				)
				if data.DefaultValue != "" {
					defaultValue = fmt.Sprintf("DEFAULT '%s'", data.DefaultValue)
				} else {
					defaultValue = "DEFAULT NULL"
				}

				if data.Type == 17 {
					defaultValue = "DEFAULT 0"
				}

				if conv.IsValueInList(data.Datatype, []string{"datetime", "longtext"}) {
					length = " null"
				} else {
					length = fmt.Sprintf("(%s)", conv.String(data.Length))
				}

				var sql = fmt.Sprintf("ALTER TABLE %s ADD %s %s%s COMMENT '%s' %s", prefix+menu.Tablename, data.Field, data.Datatype, length, data.Title, defaultValue)
				if err := sys.System.Conn(p.svcCtx, menu.Connect).Exec(sql).Error; err != nil {
					panic(err)
				}

				if data.Indexdata != "" {
					var sql = fmt.Sprintf("ALTER TABLE %s ADD %s (  `%s` )", prefix+menu.Tablename, data.Indexdata, data.Field)
					if err := sys.System.Conn(p.svcCtx, menu.Connect).Exec(sql).Error; err != nil {
						panic(err)
					}
				}
			}

			if menu.PageType == 2 && data.Type == 30 {
				var sql = fmt.Sprintf("ALTER TABLE `%s` ADD %s VARCHAR( 50 )", prefix+menu.Tablename, data.Field)
				if err := sys.System.Conn(p.svcCtx, menu.Connect).Exec(sql).Error; err != nil {
					panic(err)
				}
			}
		}
		c.Set("data", data)
		c.Next()
	}
}
